package com.hxkcloud.nurse.request;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.hxkcloud.nurse.beans.resultbeans.BaseResultBean;
import com.hxkcloud.nurse.beans.resultbeans.ListResultBean;
import com.hxkcloud.nurse.beans.resultbeans.ObjectResultBean;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 
 * @Package: com.yipong.app.request
 * @ClassName: GsonUtils.java
 * @Description:
 * @auther: allen_lee
 * @Date: 2016-2-25 下午6:27:12
 *
 */

public class GsonUtils {

	private static Gson gson;

	/**
	 * 初始化话Gson
	 * 
	 * @return Gson
	 */
	private static Gson buildGson() {
		if (gson == null) {
			GsonBuilder builder = new GsonBuilder();
			// 设置只有@Expose修饰的字段才可以映射
			builder.excludeFieldsWithoutExposeAnnotation();
			gson = builder.create();
		}
		return gson;
	}
	
	/**
	 * object to json
	 * 
	 * @param o
	 * @return
	 */
	public static String buildJson(Object o) {
		return GsonUtils.buildGson().toJson(o);
	}

	public static <T> T json2Result(String jsonStr, Class<T> cls) {
		T t = null;
		try {
			t = GsonUtils.buildGson().fromJson(jsonStr, cls);
		} catch (JsonSyntaxException e) {
			e.printStackTrace();
		}
		return t;
	}

	/**
	 * json 转对象
	 * 
	 * @param <T>
	 * 
	 * @param jsonStr
	 * @param cls
	 * @return
	 */
	public static <T> ObjectResultBean<T> json2Object(String jsonStr, Class<T> cls) {
		ObjectResultBean<T> t = null;
		try {
			Type type = type(ObjectResultBean.class, cls);
			t = GsonUtils.buildGson().fromJson(jsonStr, type);
		} catch (JsonSyntaxException e) {
			e.printStackTrace();
		}
		return t;
	}

	/** JSON转BaseBean */
	public static BaseResultBean json2BaseBean(String jsonStr) {
		BaseResultBean b = null;
		try {
			b = GsonUtils.buildGson().fromJson(jsonStr, BaseResultBean.class);
		} catch (JsonSyntaxException e) {
			e.printStackTrace();
		}
		return b;
	}
	
	/**
	 * json 转集合
	 * 
	 * @param jsonStr
	 * @param cls
	 * @return
	 */
	public static <T> ListResultBean<T> json2List(String jsonStr, Class<T> cls) {
		ListResultBean<T> t = null;
		try {
			Type type = type(ListResultBean.class, cls);
			t = GsonUtils.buildGson().fromJson(jsonStr, type);
		} catch (JsonSyntaxException e) {
			e.printStackTrace();
		}
		return t;
	}
	
	
	/**
	 * 获取泛型类的类型
	 * 
	 * @param raw
	 * @param args
	 * @return
	 */
	static ParameterizedType type(final Class raw, final Type... args) {
		return new ParameterizedType() {
			public Type getRawType() {
				return raw;
			}

			public Type[] getActualTypeArguments() {
				return args;
			}

			public Type getOwnerType() {
				return null;
			}
		};
	}
	
}
